package com.kd.crawler.common.jms;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;

import org.apache.activemq.pool.PooledConnectionFactory;

import com.kd.crawler.common.utils.PropertiesUtils;


/**
 * 链接工厂管理类
 * 自己工厂定义成了单例模式，连接池是静态块进行初始化，具体实现自己看着办
 */
public class MQPooledConnectionFactory {
	
	private static Properties properties=PropertiesUtils.getProperties("activeMQ.properties");
	
	private static PooledConnectionFactory pooledConnectionFactory;
	
	private static void initPooledConnectionFactory(){
		try {
			pooledConnectionFactory=new PooledConnectionFactory();
			pooledConnectionFactory.setProperties(properties);			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获得链接池工厂
	 */
	public static PooledConnectionFactory getPooledConnectionFactory() {
		return pooledConnectionFactory;
	}
	/**
	 * 返回链接
	 * @return
	 */
	public static Connection getConnection(){
		if(pooledConnectionFactory==null){
			initPooledConnectionFactory();
		}
		try {
			return pooledConnectionFactory.createConnection();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 返回session
	 * @param transacted
	 * @param acknowledgeMode
	 * @return
	 */
	public static Session createSession(boolean transacted, int acknowledgeMode){
		try {
			return getConnection().createSession(transacted, acknowledgeMode);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 对象回收销毁时停止链接
	 */
	@Override
	protected void finalize() throws Throwable {
		pooledConnectionFactory.stop();
		super.finalize();
	}
}